package com.kpmg.datalake.common.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.jcraft.jsch.ChannelSftp;
import com.kpmg.datalake.common.constants.Constants;
import com.kpmg.datalake.common.enums.ProjectSourceEnum;
import com.kpmg.datalake.common.enums.ProjectSyncStatusEnum;
import com.kpmg.datalake.common.enums.ResultCodeEnum;
import com.kpmg.datalake.common.service.IEntBscinfService;
import com.kpmg.datalake.common.service.IProjectService;
import com.kpmg.datalake.common.service.ProjectManagementService;
import com.kpmg.datalake.common.service.RbacFunctionService;
import com.kpmg.datalake.common.utils.EncrypUtil;
import com.kpmg.datalake.common.utils.Utils;
import com.kpmg.datalake.common.vo.ProjectVO;
import com.kpmg.datalake.common.vo.ServerResponse;
import com.kpmg.datalake.db.model.EntBscinf;
import com.kpmg.datalake.db.model.Project;
import com.kpmg.datalake.schedule.utils.ftp.SftpClient;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

@Service
public class ProjectManagementServiceImpl implements ProjectManagementService {

  private static final Logger logger = LoggerFactory.getLogger(ProjectManagementServiceImpl.class);

  @Autowired
  private IEntBscinfService entBscinfService;

  @Autowired
  private IProjectService projectService;

  @Resource
  private TaskExecutor taskExecutor;
  @Resource
  private RbacFunctionService rbacFunctionService;



  @Override
  public ServerResponse<Page<Project>> getProjectList(ProjectVO projectVO) {
    if (projectVO == null) {
      return ServerResponse.createByErrorMessage("项目信息获取未传递参数");
    }
    logger.info("开始获取项目数据...");
    Page<Project> resultList;
    try {
      resultList = projectService.getProjectList(projectVO.getPageNum(), projectVO.getPageSize(),
          projectVO.getQueryParam());
      return ServerResponse.createBySuccess("获取项目信息表成功", resultList);
    } catch (Exception e) {
      logger.error("获取项目信息失败", e);
      return ServerResponse.createByErrorMessage("项目信息获取失败");
    }
  }

  @Override
  public ServerResponse<String> testSftp(Project project) {
    ChannelSftp channel;
    SftpClient sftpClient = null;
    try {
   //  String pwd= RSAUtil.decode(project.getSftpPwd(),privateKey);
      String pwd = EncrypUtil.decryptAes(project.getSftpPwd(), Constants.ENCRY_KEY);
      sftpClient = SftpClient
          .connect(project.getSftpIp(), project.getSftpPort(), project.getSftpUser(),
             pwd, 2000, -1);
      channel = sftpClient.getChannel();
      if (CollectionUtils.isEmpty(channel.ls(project.getSftpPath()))) {
        return ServerResponse.createByErrorCodeMessage(ResultCodeEnum.CODE4035.getCode(),
            ResultCodeEnum.CODE4035.getDisplay());
      }
    } catch (Exception e) {
      logger.error("sftp连接失败", e);
      return ServerResponse.createByErrorCodeMessage(ResultCodeEnum.CODE4031.getCode(),
          ResultCodeEnum.CODE4031.getDisplay());
    } finally {
      if (sftpClient != null) {
        sftpClient.disconnect();
      }
    }
    return ServerResponse.createBySuccess();
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public ServerResponse<String> saveProjectEnt(Project project, EntBscinf entBscinf) {
    if (project == null || entBscinf == null || project.getPrjName() == null) {
      return ServerResponse.createByErrorMessage("项目信息保存失败, 未传递参数");
    }
    boolean isCreateMode = null == project.getPrjId();
    try {
      ServerResponse<String> result;
      boolean saveEntSuccess = false;
      boolean saveProjectSuccess = false;
      if (isCreateMode) {
        Project projectInfo = projectService.selectProjectByName(project.getPrjName());
        if (projectInfo != null) {
          return ServerResponse.createByErrorCodeMessage(ResultCodeEnum.CODE4032, "项目名称已存在");
        }
        String prjId = Utils.getGUID();
        String entId = Utils.getGUID();
        entBscinf.setEntId(entId);
        project.setPrjId(prjId);
        project.setEntId(entId);
        project.setPrjSource(ProjectSourceEnum.LOCAL.getCode());
        project.setSyncStatus(ProjectSyncStatusEnum.UN_INIT.getCode());
        project.setEntityBasic(entBscinf);
        result = rbacFunctionService.syncProjectUserPermissions(project);
        if (result.isSuccess()) {
          saveEntSuccess = entBscinfService.insert(entBscinf);
          saveProjectSuccess = projectService.insert(project);
        }
      } else {
        project.setEntityBasic(entBscinf);
        result = rbacFunctionService.syncProjectUserPermissions(project);
        if (result.isSuccess()) {
          saveEntSuccess = entBscinfService.updateById(entBscinf);
          saveProjectSuccess = projectService.updateById(project);
        }
      }
      if (saveEntSuccess && saveProjectSuccess) {
        logger.info("保存项目信息成功");
      } else {
        logger.error("Save Project and Entity Failed");
      }
    } catch (Exception e) {
      logger.error("保存项目信息失败", e);
      return ServerResponse.createByErrorCodeMessage(ResultCodeEnum.CODE4015.getCode(),
          ResultCodeEnum.CODE4015.getDisplay());
    }
    return ServerResponse.createBySuccess();
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public ServerResponse<String> sysProject(Project project) {
    taskExecutor.execute(() -> {
      try {
        projectService.syncProjectData(project.getPrjId());
      } catch (Exception e) {
        logger.error(e.getMessage(), e);
      }
    });
    return ServerResponse.createBySuccess();
  }
}
